import sys
import os
import pickle

from entitymanager import*

class level(object):
    """Really just a class for saving data"""

    def __init__(self,game, camera, player):
        self.levelID = 1
        self.levelData = []
        self.game = game
        

    def save(self):
        """Saves a level, if the folder "Levels" doesn't exist it makes one"""
        #self.levelData['player'] = self.game.player
        #self.levelData['entities'] = self.game.entitymanager.entities
        #self.levelData['camera'] = self.game.camera

        for en in self.game.entitymanager.entities:
            en.onSave(self.game.entitymanager, self.levelData)

        if(not os.path.exists('levels')):
            os.makedirs('levels')

        pathToFile = os.path.join("levels", "level-"+str(self.levelID))
        file = open(pathToFile, 'wb')

        
        try:
            pickle.dump(self.levelData, file)
        except:
            print 'Uh-oh!'

    def load(self):
        """Loads a level, will crash if the level file does not exist"""
        if(not os.path.exists('levels')):
            os.makedirs('levels')

        pathToFile = os.path.join("levels", "level-"+str(self.levelID))

        try:
            file = open(pathToFile, 'rb')
            levelData = pickle.load(file)
            self.game.entitymanager.load(levelData)

        except:
            #If the level data is corrupted, or does not exist, make a temporary level so it's possible to make a new one.
            levelData = {}
            newPlayer = player(self.game.entitymanager)
            #levelData['player'] = newPlayer
            #levelData['entities'] = []
            #levelData['entities'].append(newPlayer)

            defaultPlat = platform(self.game.entitymanager)
            defaultPlat.rect.width = 400
            defaultPlat.rect.topleft = (0,200)
            #levelData['entities'].append(defaultPlat)

            dog = companion(self.game.entitymanager)
            newPlayer.dog = dog
            dog.player = newPlayer
            dog.owner = newPlayer
           # levelData['entities'].append(dog)
            self.game.entitymanager.addEntity(newPlayer, newPlayer.update)
            self.game.entitymanager.addEntity(dog, newPlayer.update)
            self.game.entitymanager.addEntity(defaultPlat, newPlayer.update)
            self.game.player = newPlayer
            self.game.camera.setFocus(newPlayer)
            
            
            Movable = moveable(self.game.entitymanager)
            Movable.player = newPlayer
            Movable.dog = dog
            self.game.entitymanager.addEntity(Movable, True)
            
            Trigger = trigger(self.game.entitymanager)
            Trigger.setplayer(newPlayer)
            Trigger.companion = dog
            Trigger.camera = self.game.camera









        
        



        

